﻿using Common.Core;
using Common.Core.HttpPolly;
using Microsoft.Extensions.DependencyInjection;
using Polly;
using Polly.Extensions.Http;
using Polly.Timeout;

namespace Domain.Infrastructure.ServiceExtensions
{
    public static class HttpClientSetup
    {
        public static IServiceCollection AddHttpClientSetup(this IServiceCollection services)
        {
            #region #region Polly策略
            var retryPolicy = HttpPolicyExtensions
                    .HandleTransientHttpError()
                    .Or<TimeoutRejectedException>() // 若超时则抛出此异常
                    .WaitAndRetryAsync(new[]
                    {
                    TimeSpan.FromSeconds(10),
                    TimeSpan.FromSeconds(30),
                    TimeSpan.FromSeconds(60)
                    });
            // 为每个重试定义超时策略
            var timeoutPolicy = Policy.TimeoutAsync<HttpResponseMessage>(30); 
            #endregion

            services.AddHttpClient(HttpEnum.MyWeb.ToString(), c =>
            {
                c.BaseAddress = new Uri(ConfigurationUtil.App("MyWebInfo", "ApiUrl"));
                c.DefaultRequestHeaders.Add("Accept", "application/json");
            })
                //.AddPolicyHandler(retryPolicy)// 将超时策略放在重试策略之内，每次重试会应用此超时策略
                .AddPolicyHandler(timeoutPolicy);

            //自我管理注册
            services.AddSingleton<IHttpPollyHelper, HttpPollyHelper>();

            return services;

        }
    }
}
